package com.hxh.wechat.model

import android.content.Context
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.hxh.wechat.api.UserApi
import com.hxh.wechat.util.DBUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException


/**
 * 保存用户聊天消息历史数据
 */
fun saveUserChatHistory(chatHistory: ChatHistory, context: Context) {
    var chatKey = "chat-" + chatHistory.myId + "-" + chatHistory.friendId;
    //查看自己的聊天记录
    var chatHistoryList: ArrayList<ChatHistory>? =
        getUserChatHistoryData(context, chatHistory.friendId)
    if (chatHistoryList == null) {
        chatHistoryList = ArrayList()
    }
    chatHistoryList.add(chatHistory)
    DBUtil.setData(context, chatKey, DBUtil.getGson().toJson(chatHistoryList))
}

fun coverUserChatHistory(
    chatHistoryList: ArrayList<ChatHistory>,
    friendId: String,
    context: Context
) {
    var chatKey = "chat-" + DBUtil.getUser(context)?.id + "-" + friendId;
    DBUtil.setData(context, chatKey, DBUtil.getGson().toJson(chatHistoryList))
}


/**
 *  聊天的快照,仅仅保持了聊天最后一条消息
 */
fun saveUserChatSnapshot(chatSnapshot: ChatSnapshot, context: Context) {
    var chatKey = "chat-snapshot" + chatSnapshot.myId
    //从本地缓存获取快照聊天记录是否存在
    var chatSnapshotList: ArrayList<ChatSnapshot>? = getUserChatSnapshot(context)
    if (chatSnapshotList == null) {
        chatSnapshotList = ArrayList()
    } else {

        var it = chatSnapshotList.iterator()
        while (it.hasNext()) {
            val item = it.next()
            if (item.friendId == chatSnapshot.friendId) {
                //删除该快照
                it.remove()
            }
        }
    }
    chatSnapshotList.add(chatSnapshot);
    //写入数据
    DBUtil.setData(context, chatKey, DBUtil.getGson().toJson(chatSnapshotList))
}


fun getUserChatSnapshot(context: Context): ArrayList<ChatSnapshot>? {
    var chatKey = "chat-snapshot" + DBUtil.getUser(context)?.id
    var string = DBUtil.getDB(context)?.getString(chatKey, "[]")
    return DBUtil.getGson().fromJson<ArrayList<ChatSnapshot>>(
        string,
        object : TypeToken<ArrayList<ChatSnapshot>>() {}.type
    );
}

//获取用户通过ID
fun getUserById(con: Context, id: String): ContactFriend? {
    var contactFriends = DBUtil.getGson().fromJson<ArrayList<ContactFriend>>(
        DBUtil.getDB(con)?.getString("contactList", "[]"),
        object : TypeToken<ArrayList<ContactFriend>>() {}.type
    )
    for (contactFriend in contactFriends) {
        if (contactFriend.friendUserId == id) {
            return contactFriend
        }
    }
    return null;
}

//保存用户通讯录数据
fun setContactList(con: Context) {
    var user = DBUtil.getUser(con);
    UserApi.myFriends(user!!.id)?.enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            println("Failed.")
            println(e.stackTrace.toString())
        }

        @Throws(IOException::class)
        override fun onResponse(call: Call, response: Response) {
            val responseData = response.body?.string()
            var contactListResult =
                DBUtil.getGson().fromJson(responseData, JsonObject::class.java)
                    .getAsJsonArray("data");
            DBUtil.setData(
                con, "contactList", contactListResult.toString()
            )

        }
    })
}

fun getUserChatHistoryData(
    context: Context,
    friendId: String
): ArrayList<ChatHistory>? {
    var chatKey = "chat-" + DBUtil.getUser(context)!!.id + "-" + friendId;
    return DBUtil.getGson().fromJson<ArrayList<ChatHistory>>(
        DBUtil.getDB(context)?.getString(chatKey, "[]"),
        object : TypeToken<ArrayList<ChatHistory>>() {}.type
    );
}